package py.com.fms.fms.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.faces.model.SelectItem;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports
import py.com.fms.exception.CommonException;
import py.com.fms.session.ServiceSqlMap;

import py.com.fms.fms.bean.CountryBean;
import py.com.fms.fms.bean.CurrencyBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.persistence.services.CountryServices;
import py.com.fms.fms.persistence.services.CurrencyServices;
import py.com.fms.fms.persistence.services.UsersServices;

import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.*;

@SuppressWarnings("unused")
@Name("editCountry")
@Scope(ScopeType.SESSION)
public class EditCountry {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
//	@In("#{withinHolder}")
//	private WithinHolder aid;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	private DateAssistant dateAssist;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	// Attribute used for saving and deleting
	private CountryBean country;
	
	// Services
	private CurrencyServices crSrv;
	private CountryServices cnSrv;
	private UsersServices usSrv;
	
	// Collections
	private Collection<CountryBean> allCountries;
	

	// Attribute used for editing or updating
	private CountryBean editCountry;
	
	
//	Necessary Attributes;


	 

	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();
			
			if(credentials != null){
				System.out.println("Credenciales Encontradas");
				this.getUser().setUserName(credentials.getUsername());
				System.out.println("User Name: " + this.getUser().getUserName());
				user = usSrv.getUserDataByName(this.getUser().getUserName());
				this.setUser(user);
				System.out.println("User: " + this.getUser());
			}else{	
				System.out.println("Credenciales Nulas");
			}
			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	
	public void initBeans(){
		
		if (country == null){
			country = new CountryBean();
			country.setStatus(true);
		}
		
		if (editCountry == null){
			editCountry = new CountryBean();
		}
		
		if (user == null){
			user = new UsersBean();
		}
		

		
	}
	
	public void initServices() throws CommonException{
		
		if (cnSrv == null){
			cnSrv = new CountryServices(this.sqlMap.getConfig());
		}
		
		if (crSrv == null){
			crSrv = new CurrencyServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
//		if(aid == null){
//			aid = new WithinHolder();
//		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allCountries == null){
			allCountries = new ArrayList<CountryBean>();
		}
		
	

	}

	public void cleanData(){
		
		// Cleaning Beans
		
		country = null;	
		editCountry = null;
		user = null;
		
		// Cleaning Services
		crSrv = null;
		crSrv = null;
		usSrv = null;

		// Cleaning Assistants
//		aid = null;
		convert = null;
		dateAssist = null;
		
		// Cleaning Collections
		allCountries = null;
		
	}
	
	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			CountryServices admSrv = new CountryServices(this.sqlMap.getConfig());
			this.setAllCountries(admSrv.getAllCountry());
			for (CountryBean country : this.getAllCountries()) {
				System.out.println(country.getCod() + " - " + country.getDescrip());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}
	
	
	// Used to cancel
	public String cancelData() {
		//this.facesMessages.clear();
		this.setInitVar("S");
		this.cleanData();
		return null;
	}

		

	// Used for data saving process
	public String saveNewData() throws ParseException{
		try {
//			this.facesMessages.clear();
			CountryBean newCountry = new CountryBean();

			today = DateAssistant.getCurrentDate();


			if (this.getCountry() == null) {
				System.out.println("Country == null");
				throw new CommonException("Not instantiated entity");
			}
			System.out.println("Before setting values");
			System.out.println("Currency COD: " + this.getCountry().getCurrencyData().getCod());
			
			// Setting field values
			newCountry.setCod(convert.convertField(this.getCountry().getCod()));
			newCountry.setDescrip(convert.convertField(this.getCountry().getDescrip()));
			newCountry.setIso(convert.convertField(this.getCountry().getIso()));
			newCountry.setIdCurrency(this.getCountry().getCurrencyData().getId());
			newCountry.setStatus((this.getCountry().getStatus()));
			newCountry.setStartDate(this.today);
			newCountry.setUserIns(1);

			cnSrv.saveNewCountry(newCountry);
			
			// Cleaning field values
			newCountry = null;

			
			// Setting Initialization VAR
			this.setInitVar("S");
			return null;
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.setCountry(null);
		}
		return "";
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (CountryBean bean : this.getAllCountries()) {
			if(bean.getId() == id){
				this.setEditCountry(bean);
				this.getEditCountry().setCurrencyData(crSrv.getCurrencyData(bean.getIdCurrency()));
				return;
			}			
		}	
	}
	
	public void dataToEditUpd(){
		try {
			
			this.getEditCountry().setCod(convert.convertField(this.getEditCountry().getCod()));
			this.getEditCountry().setDescrip(convert.convertField(this.getEditCountry().getDescrip()));
			cnSrv.updateCountry(this.getEditCountry());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (CountryBean bean: this.getAllCountries()){
			if (bean.getId() == id) {
				try {
					cnSrv.deleteCountryById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}
	

	// List of Countries for suggestion
	
	private SelectItem [] countries = new SelectItem[]{
			new SelectItem("Afganistan"),
	        new SelectItem("Africa del Sur"),
	        new SelectItem("Albania"),
	        new SelectItem("Alemania"),
	        new SelectItem("Andorra"),
	        new SelectItem("Angola"),
	        new SelectItem("Antigua y Barbuda"),
	        new SelectItem("Antillas Holandesas"),
	        new SelectItem("Arabia Saudita"),
	        new SelectItem("Argelia"),
	        new SelectItem("Argentina"),
	        new SelectItem("Armenia"),
	        new SelectItem("Aruba"),
	        new SelectItem("Australia"),
	        new SelectItem("Austria"),
	        new SelectItem("Azerbaijan"),
	        new SelectItem("Bahamas"),
	        new SelectItem("Bahrain"),
	        new SelectItem("Bangladesh"),
	        new SelectItem("Barbados"),
	        new SelectItem("Belarusia"),
	        new SelectItem("Belgica"),
	        new SelectItem("Belice"),
	        new SelectItem("Benin"),
	        new SelectItem("Bermudas"),
	        new SelectItem("Bolivia"),
	        new SelectItem("Bosnia"),
	        new SelectItem("Botswana"),
	        new SelectItem("Brasil"),
	        new SelectItem("Brunei Darussulam"),
	        new SelectItem("Bulgaria"),
	        new SelectItem("Burkina Faso"),
	        new SelectItem("Burundi"),
	        new SelectItem("Butan"),
	        new SelectItem("Camboya"),
	        new SelectItem("Camerun"),
	        new SelectItem("Canada"),
	        new SelectItem("Cape Verde"),
	        new SelectItem("Chad"),
	        new SelectItem("Chile"),
	        new SelectItem("China"),
	        new SelectItem("Chipre"),
	        new SelectItem("Colombia"),
	        new SelectItem("Comoros"),
	        new SelectItem("Congo"),
	        new SelectItem("Corea del Norte"),
	        new SelectItem("Corea del Sur"),
	        new SelectItem("Costa de Marf�l"),
	        new SelectItem("Costa Rica"),
	        new SelectItem("Croacia"),
	        new SelectItem("Cuba"),
	        new SelectItem("Dinamarca"),
	        new SelectItem("Djibouti"),
	        new SelectItem("Dominica"),
	        new SelectItem("Ecuador"),
	        new SelectItem("Egipto"),
	        new SelectItem("El Salvador"),
	        new SelectItem("Emiratos Arabes Unidos"),
	        new SelectItem("Eritrea"),
	        new SelectItem("Eslovenia"),
	        new SelectItem("Espa�a"),
	        new SelectItem("Estados Unidos"),
	        new SelectItem("Estonia"),
	        new SelectItem("Etiopia"),
	        new SelectItem("Fiji"),
	        new SelectItem("Filipinas"),
	        new SelectItem("Finlandia"),
	        new SelectItem("Francia"),
	        new SelectItem("Gabon"),
	        new SelectItem("Gambia"),
	        new SelectItem("Georgia"),
	        new SelectItem("Ghana"),
	        new SelectItem("Granada"),
	        new SelectItem("Grecia"),
	        new SelectItem("Groenlandia"),
	        new SelectItem("Guadalupe"),
	        new SelectItem("Guam"),
	        new SelectItem("Guatemala"),
	        new SelectItem("Guayana Francesa"),
	        new SelectItem("Guerney"),
	        new SelectItem("Guinea"),
	        new SelectItem("Guinea-Bissau"),
	        new SelectItem("Guinea Equatorial"),
	        new SelectItem("Guyana"),
	        new SelectItem("Haiti"),
	        new SelectItem("Holanda"),
	        new SelectItem("Honduras"),
	        new SelectItem("Hong Kong"),
	        new SelectItem("Hungria"),
	        new SelectItem("India"),
	        new SelectItem("Indonesia"),
	        new SelectItem("Inglaterra"),
	        new SelectItem("Irak"),
	        new SelectItem("Iran"),
	        new SelectItem("Irlanda"),
	        new SelectItem("Islandia"),
	        new SelectItem("Islas Caiman"),
	        new SelectItem("Islas Faroe"),
	        new SelectItem("Islas Malvinas"),
	        new SelectItem("Islas Marshall"),
	        new SelectItem("Islas Solomon"),
	        new SelectItem("Islas Virgenes"),
	        new SelectItem("Israel"),
	        new SelectItem("Italia"),
	        new SelectItem("Jamaica"),
	        new SelectItem("Japon"),
	        new SelectItem("Jersey"),
	        new SelectItem("Jordania"),
	        new SelectItem("Kazakhstan"),
	        new SelectItem("Kenia"),
	        new SelectItem("Kiribati"),
	        new SelectItem("Kuwait"),
	        new SelectItem("Kyrgyzstan"),
	        new SelectItem("Laos"),
	        new SelectItem("Latvia"),
	        new SelectItem("Lesotho"),
	        new SelectItem("Libano"),
	        new SelectItem("Liberia"),
	        new SelectItem("Libia"),
	        new SelectItem("Liechtenstein"),
	        new SelectItem("Lituania"),
	        new SelectItem("Luxemburgo"),
	        new SelectItem("Macao"),
	        new SelectItem("Macedionia"),
	        new SelectItem("Madagascar"),
	        new SelectItem("Malasia"),
	        new SelectItem("Malawi"),
	        new SelectItem("Maldivas"),
	        new SelectItem("Mali"),
	        new SelectItem("Malta"),
	        new SelectItem("Marruecos"),
	        new SelectItem("Martinica"),
	        new SelectItem("Mauricio"),
	        new SelectItem("Mauritania"),
	        new SelectItem("Mexico"),
	        new SelectItem("Micronesia"),
	        new SelectItem("Moldova"),
	        new SelectItem("Monaco"),
	        new SelectItem("Mongolia"),
	        new SelectItem("Mozambique"),
	        new SelectItem("Myanmar"),
	        new SelectItem("Namibia"),
	        new SelectItem("Nepal"),
	        new SelectItem("Nicaragua"),
	        new SelectItem("Niger"),
	        new SelectItem("Nigeria"),
	        new SelectItem("Noruega"),
	        new SelectItem("Nueva Caledonia"),
	        new SelectItem("Nueva Zealandia"),
	        new SelectItem("Oman"),
	        new SelectItem("Pakistan"),
	        new SelectItem("Palestina"),
	        new SelectItem("Panama"),
	        new SelectItem("Papua Nueva Guinea"),
	        new SelectItem("Paraguay"),
	        new SelectItem("Peru"),
	        new SelectItem("Polinesia Francesa"),
	        new SelectItem("Polonia"),
	        new SelectItem("Portugal"),
	        new SelectItem("Puerto Rico"),
	        new SelectItem("Qatar"),
	        new SelectItem("Reino Unido"),
	        new SelectItem("Republica Centroafricana"),
	        new SelectItem("Republica Checa"),
	        new SelectItem("Republica Democratica del Congo"),
	        new SelectItem("Republica Dominicana"),
	        new SelectItem("Republica Eslovaca"),
	        new SelectItem("Reunion"),
	        new SelectItem("Ruanda"),
	        new SelectItem("Rumania"),
	        new SelectItem("Rusia"),
	        new SelectItem("Sahara"),
	        new SelectItem("Samoa"),
	        new SelectItem("San Cristobal-Nevis"),
	        new SelectItem("San Marino"),
	        new SelectItem("San Vincente y las Granadinas"),
	        new SelectItem("Santa Lucia"),
	        new SelectItem("Santa Sede"),
	        new SelectItem("Sao Tome & Principe"),
	        new SelectItem("Senegal"),
	        new SelectItem("Seychelles"),
	        new SelectItem("Sierra Leona"),
	        new SelectItem("Singapur"),
	        new SelectItem("Siria"),
	        new SelectItem("Somalia"),
	        new SelectItem("Sri Lanka"),
	        new SelectItem("Sudan"),
	        new SelectItem("Suecia"),
	        new SelectItem("Suiza"),
	        new SelectItem("Sur Africa"),
	        new SelectItem("Surinam"),
	        new SelectItem("Swaziland"),
	        new SelectItem("Tailandia"),
	        new SelectItem("Taiwan"),
	        new SelectItem("Tajikistan"),
	        new SelectItem("Tanzania"),
	        new SelectItem("Timor Oriental"),
	        new SelectItem("Togo"),
	        new SelectItem("Tonga"),
	        new SelectItem("Trinidad & Tobago"),
	        new SelectItem("Tunisia"),
	        new SelectItem("Turkmenistan"),
	        new SelectItem("Turquia"),
	        new SelectItem("Ucrania"),
	        new SelectItem("Uganda"),
	        new SelectItem("Union Europea"),
	        new SelectItem("Uruguay"),
	        new SelectItem("Uzbekistan"),
	        new SelectItem("Vanuatu"),
	        new SelectItem("Venezuela"),
	        new SelectItem("Vietnam"),
	        new SelectItem("Yemen"),
	        new SelectItem("Yugoslavia"),
	        new SelectItem("Zambia"),
	        new SelectItem("Zimbabwe"),
			
	};

	// Getters and Setters

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public CountryBean getCountry() {
		return country;
	}

	public void setCountry(CountryBean country) {
		this.country = country;
	}

	public Collection<CountryBean> getAllCountries() {
		return allCountries;
	}

	public void setAllCountries(Collection<CountryBean> allCountries) {
		this.allCountries = allCountries;
	}

	public CountryBean getEditCountry() {
		return editCountry;
	}

	public void setEditCountry(CountryBean editCountry) {
		this.editCountry = editCountry;
	}

	public SelectItem[] getCountries() {
		return countries;
	}

	public void setCountries(SelectItem[] countries) {
		this.countries = countries;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	

}


